import time

from fastapi import APIRouter
import aiohttp
import asyncio
from app.common.result import Result


router = APIRouter()


@router.get("/test")
async def test():
    return Result.success(msg = "我还活着",data= await test_concurrency())


@router.get("/mock_test")
async def test():
    tasks = [mock_request(i) for i in range(5)]
    return Result.success(msg = "我还活着",data = await asyncio.gather(*tasks))

async def fetch(url):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            return await response.text()

async def test_concurrency():
    urls = ["https://httpbin.org/delay/1"] * 10  # 模拟延迟1秒的请求
    tasks = [fetch(url) for url in urls]
    await asyncio.gather(*tasks)  # 应该总耗时≈1秒（而不是5秒）
    print(tasks)


async def mock_request(idx):
    start = time.time()
    await asyncio.sleep(5)  # 模拟延迟
    print(f"Mock {idx} done in {time.time() - start:.2f}s")
    return f"result_{idx}"

